package pl.wroc.pwr.mss.server.service.impl;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import pl.wroc.pwr.mss.logic.domain.Playlist;
import pl.wroc.pwr.mss.logic.domain.Song;
import pl.wroc.pwr.mss.server.service.PlaylistService;
import pl.wroc.pwr.mss.server.service.SongService;

/**
 * Serwerowa implementacja serwisu dla encji Playlist.
 * 
 * @author mjagus
 */
public class PlaylistServiceServerImpl extends GenericServiceImpl<Playlist, Long> implements PlaylistService
{
    /**
     * Logger tej klasy.
     */
    private static final Logger log = Logger.getLogger(PlaylistServiceServerImpl.class);

    /**
     * Filtr plikow z rozszerzeniem mp3.
     */
    private static final Mp3FileFilter mp3FileFilter = new Mp3FileFilter();

    /**
     * Serwis dla encji song.
     */
    private SongService songService;

    @Override
    public Playlist createPlaylistForDirectory(File directory)
    {
        Playlist playlist = new Playlist();
        playlist.setSongs(new ArrayList<Song>());

        if(directory.isDirectory())
        {
            log.info("Reading directory: " + directory.getPath());
            File[] files = directory.listFiles(mp3FileFilter);

            playlist.setName(directory.getName());
            playlist.getSongs().addAll(songService.createSongsForFiles(files));
        }
        else
            log.error(directory.getName() + " is not a directory!");

        return playlist;
    }

    /**
     * @return Serwis dla encji Song
     */
    public SongService getSongService()
    {
        return songService;
    }

    /**
     * @param songService Serwis dla encji song
     */
    public void setSongService(SongService songService)
    {
        this.songService = songService;
    }

    /**
     * Filtr przepuszczajacy tylko pliki z rozszerzeniem mp3.
     * 
     * @author mjagus
     */
    private static class Mp3FileFilter implements FileFilter
    {
        @Override
        public boolean accept(File f)
        {
            return f.getName().endsWith(".mp3");
        }
    }
}
